package com.rancedxk.monitor.device.provider.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.jfinal.core.JFinal;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.rancedxk.monitor.device.Device;
import com.rancedxk.monitor.device.provider.IDeviceProvider;

import cn.hutool.core.bean.BeanUtil;

public class DbProvider implements IDeviceProvider{
	
	private static final String configName = "dbProvider";
	
	static {
		//配置数据库连接池
		//配置Druid插件，可以监控查看SQL执行情况
		DruidPlugin dbPlugin = new DruidPlugin(PropKit.get("device.provider.db.url"), PropKit.get("device.provider.db.username"), PropKit.get("device.provider.db.password"));
		dbPlugin.start();
		//配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(configName,dbPlugin);
		arp.setDialect(new MysqlDialect());
		//是否在控制台显示所使用的SQL原文，用于调试
		arp.setShowSql(JFinal.me().getConstants().getDevMode());
		arp.start();
	}
	
	private DbPro db(){
		return Db.use(configName);
	}

	@Override
	public boolean isContain(String code) {
		return db().queryLong("SELECT COUNT(1) FROM t_device WHERE code=?",code)!=0;
	}

	@Override
	public Device get(String code) {
		Record record = db().findFirst("SELECT * FROM t_device WHERE code=?",code);
		return BeanUtil.mapToBean(record.getColumns(), Device.class, true);
	}

	@Override
	public Collection<Device> getAll() {
		Collection<Device> deviceList = new ArrayList<Device>();
		List<Record> recordList = db().find("SELECT * FROM t_device");
		if(recordList!=null){
			for(Record item : recordList){
				deviceList.add(BeanUtil.mapToBean(item.getColumns(), Device.class, true));
			}
		}
		return deviceList;
	}
}
